<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'bas:cus:coreKhda:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsBasCusCoreKhdaForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CoreKhda, coreKhdaSave, coreKhdaForm } from '/@/api/bas/cus/coreKhda';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bas.cus.coreKhda');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CoreKhda>({} as CoreKhda);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增客户档案') : t('编辑客户档案'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单位编码'),
      field: 'khdaDwbm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: false,
      dynamicDisabled: true,
    },
    {
      label: t('单位简称'),
      field: 'khdaDwjc',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('单位全称'),
      field: 'khdaDwqc',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('单位分类'),
      field: 'khdaDwfl',
      component: 'Select',
      componentProps: {
        dictType: 'car_cus_cls',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('业务员'),
      field: 'khdaYwy',
      fieldLabel: 'person.userName',
      component: 'ListSelect',
      componentProps: {
        selectType: 'empUserSelect',
      },
    },
    {
      label: t('结算方式'),
      field: 'khdaJsfs',
      component: 'Select',
      componentProps: ({ formModel }) => {
        return {
          dictType: 'car_settle_tpye',
          allowClear: true,
          onChange: (v) => {
            if (v === '1') {
              // 按订单结算
              updateSchema([
                { field: 'khdaJszq', dynamicDisabled: true },
                { field: 'khdaSxed', required: false, dynamicDisabled: true },
              ]);
            } else if (v === '2') {
              // 按周期结算
              updateSchema([
                { field: 'khdaJszq', required: true, dynamicDisabled: false },
                { field: 'khdaSxed', dynamicDisabled: true },
              ]);
            } else if (v === '3') {
              // 按额度结算
              updateSchema([
                { field: 'khdaJszq', required: false, dynamicDisabled: true },
                { field: 'khdaSxed', required: true, dynamicDisabled: false },
              ]);
            } else {
              updateSchema([
                { field: 'khdaJszq', required: false, dynamicDisabled: false },
                { field: 'khdaSxed', required: false, dynamicDisabled: false },
              ]);
            }
          },
          onSelect: (v) => {
            formModel['khdaJszq'] = '';
            formModel['khdaSxed'] = '';
          },
        };
      },
      required: true,
    },
    {
      label: t('结算周期'),
      field: 'khdaJszq',
      component: 'Select',
      componentProps: {
        dictType: 'car_settle_cycle',
        allowClear: true,
      },
    },
    {
      label: t('授信额度'),
      field: 'khdaSxed',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('单位地址'),
      field: 'khdaDwdz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 600,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await coreKhdaForm(data);
    record.value = (res.coreKhda || {}) as CoreKhda;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    updateSchema([
      {
        field: 'khdaDwbm',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        khdaDwbm: record.value.khdaDwbm,
        khdaDwjc: record.value.khdaDwjc,
      };
      // console.log('submit', params, data, record);
      const res = await coreKhdaSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
